package com.magic.zhixin.handler.DelayTask;

import lombok.Data;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayedTask implements Delayed{
    private String notes;//说明
    private Long executeTime;//执行时间，单位ms，
//    private Integer taskType;//任务类型，可为空  0:定时开奖 1：订单自动取消 2:秒合约结算
    private Integer taskType;
    private String bussinessId;//业务号，对于接入者必须唯一标识
    private Date exeDateTime;
//    /**初始化定时队列类型*/
//    public static int INIT_TASK = 0;
//    /**普通定时任务**/
//    public static int COMM_TASK = 1;

//    /**taskType:定时任务类型  0-初始化任务，1-普通任务***/

    /**
     * 定时任务模型
     * @param taskType  类型，--可为空
     * @param bussinessId  业务号 ，不可为空
     * @param exeTime  执行时间
     */
    public DelayedTask(Integer taskType, String bussinessId, Date exeTime){
        this.taskType = taskType;
        this.bussinessId = bussinessId;
        try {
            this.executeTime = exeTime.getTime();
        } catch (Exception e) {
            this.executeTime = System.currentTimeMillis();
        }
        this.exeDateTime = exeTime;
    }


//    private DelayedTask(String taskName, long delayTime, TimeUnit delayTimeUnit) {
//        this.name = taskName;
//        this.delayTime = delayTime;
//        this.delayTimeUnit = delayTimeUnit;
//        this.executeTime = System.currentTimeMillis() + delayTimeUnit.toMillis(delayTime);
//    }
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executeTime - System.currentTimeMillis(),
                TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if(this.getDelay(TimeUnit.MILLISECONDS) >
                o.getDelay(TimeUnit.MILLISECONDS)) {
            return 1;
        }else if(this.getDelay(TimeUnit.MILLISECONDS) <
                o.getDelay(TimeUnit.MILLISECONDS)) {
            return -1;
        }
        return 0;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final DelayedTask other = (DelayedTask) obj;
        //对于一个定时任务，其业务ID和业务type相同则认定为同一个任务
        if(!this.bussinessId.equals(other.bussinessId))
            return false;
        if (taskType != null && taskType != other.taskType) {
            return false;
        }
//        if(this.delayTask.getBusinessType().intValue() != other.delayTask.getBusinessType().intValue())
//            return false;
        //时间上总会有误差
//        if(!this.delayTask.getStarttime().equals(other.delayTask.getStarttime()))
//            return false;
        return true;

    }
}
